package com.fg.cloud.agency.controller.account;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fg.cloud.agency.controller.BaseAgencyController;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.AgencyBill;
import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.manager.entry.agency.AgencyBillEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyBillVo;
import com.fg.cloud.manager.entry.order.OrderPaymentEntity;
import com.fg.cloud.manager.service.agency.AgencyBillService;

/**
 * Description:经销商端 账单流水controller
 * 
 * @author shaoqiping
 * @date 2017年8月21日下午2:31:13
 */
@Controller
@RequestMapping("/agencyFacBill")
public class AgencyFacBillController extends BaseAgencyController {
	@Autowired
	private AgencyBillService billService;

	/**
	 * Description:新增订单流水
	 * 
	 * @param request
	 * @param response
	 * @param billEntity
	 * @author shaoqiping
	 * @date 2017年8月25日上午11:01:27
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/addOrderFlow", method = { RequestMethod.POST })
	@ResponseBody
	public void insertOrderFlow(HttpServletRequest request, HttpServletResponse response, AgencyBillEntity billEntity,
			boolean mark) {
		try {
			if (billEntity == null || LongUtils.isEmpty(billEntity.getOrderId()) || billEntity.getTransInfo() == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择要付款的订单");
				return;
			}
			billEntity.setFacId(getCurrentAgencyUser().getFacId());
			billEntity.setAgeId(getCurrentAgencyUser().getAgeId());
			billEntity.setTransTime(new Date());
			boolean temp = getCurrentAgencyUser().getAgencySetup().getReceivablesFlag() > 0;
			boolean flag = false;
			if (mark) {
				flag = billService.insertSelective(billEntity, temp);
			} else {
				flag = billService.insertDouble(billEntity, temp);
			}
			if (flag) {
				doResult(response, true, StatusCode.SAVESUCCESS, null, "交易成功");
			} else {
				doResult(response, false, StatusCode.SAVEERROR, null, "交易失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:新增充值流水
	 * 
	 * @param request
	 * @param response
	 * @param billEntity
	 * @author shaoqiping
	 * @date 2017年8月25日上午8:48:10
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/addAccountFlow", method = { RequestMethod.POST })
	@ResponseBody
	public void insertAccountFlow(HttpServletRequest request, HttpServletResponse response,
			AgencyBillEntity billEntity) {
		try {
			if (billEntity == null || billEntity.getAmount() == null || billEntity.getTransInfo() == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请填写必要信息");
				return;
			}
			if (billEntity.getTransInfo() < 1 || billEntity.getTransInfo() > 4) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择支付方式");
				return;
			}
			billEntity.setFacId(getCurrentAgencyUser().getFacId());
			billEntity.setAgeId(getCurrentAgencyUser().getAgeId());
			billEntity.setTransTime(new Date());
			boolean temp = getCurrentAgencyUser().getAgencySetup().getReceivablesFlag() > 0;
			if (billEntity.getTransInfo() == AgencyBill.REFUND) {
				billEntity.setConfirmTime(new Date());
				billEntity.setConfirmAmount(billEntity.getAmount());
				billEntity.setStatus(AgencyBill.STATUS);
			} else {
				if (!temp) {
					if (billEntity.getTransMode() <= AgencyBill.CONFIRM) {
						billEntity.setConfirmTime(new Date());
						billEntity.setConfirmAmount(billEntity.getAmount());
						billEntity.setStatus(AgencyBill.STATUS);
					}
				}
			}
			boolean flag = billService.insert(billEntity, temp);
			if (flag) {
				if (billEntity.getTransInfo() == AgencyBill.AMOUNT_ADD) {
					doResult(response, true, StatusCode.SAVESUCCESS, null, "充值成功");
				}else {
					doResult(response, true, StatusCode.SAVESUCCESS, null, "退款成功");
				}
			} else {
				if (billEntity.getTransInfo() == AgencyBill.AMOUNT_ADD) {
					doResult(response, false, StatusCode.SAVEERROR, null, "充值失败");
				}else {
					doResult(response, false, StatusCode.SAVEERROR, null, "退款失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:查询订单付款详情(分页)
	 * 
	 * @param request
	 * @param response
	 * @param orderId
	 * @author shaoqiping
	 * @date 2017年9月14日下午3:06:33
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findOrderAmountList", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findOrderAmountList(HttpServletRequest request, HttpServletResponse response,Integer page, Integer rows,
			String sort, String order, Long orderId) {
		try {
			if(orderId==null||LongUtils.isEmpty(orderId)){
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择相应订单");
				return;
			}
			if (page == null || page <= 0) {
				page = 1;
			}
			if (rows == null || rows <= 0) {
				rows = 10;
			}
			PageUtils<AgencyBillEntity> pageinfo = new PageUtils<AgencyBillEntity>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("id", orderId);
			pageinfo.setCondition(condition);

			billService.findOrderAmount(pageinfo);
			
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:查询订单付款详情
	 * 
	 * @param request
	 * @param response
	 * @param orderId
	 * @author shaoqiping
	 * @date 2017年9月14日下午3:06:33
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findOrderAmount", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findOrderAmount(HttpServletRequest request, HttpServletResponse response,Long orderId) {
		try {
			if(orderId==null||LongUtils.isEmpty(orderId)){
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择相应订单");
				return;
			}
			doResult(response, true, StatusCode.FINDSUCCESS, billService.findOrderPayment(orderId), ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:查询未完成付款的订单
	 *
	 * @param request
	 * @param response
	 * @author shaoqiping
	 * @date 2017年9月8日下午3:36:20
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findUnfinished", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findUnfinished(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<OrderPaymentEntity> needPays = billService.findUnfinished(getCurrentAgencyUser().getFacId(),
					getCurrentAgencyUser().getAgeId());
			BigDecimal amount = BigDecimal.ZERO;
			for (OrderPaymentEntity orderPaymentEntity : needPays) {
				amount = amount.add(orderPaymentEntity.getNeedPay());
			}
			Map<String,BigDecimal> map = new HashMap<>();
			map.put("amount", amount);
			doResult(response, true, StatusCode.FINDSUCCESS,map,ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:选择未完成订单进行付款
	 *
	 * @param request
	 * @param response
	 * @param keyValue
	 * @param billEntity
	 * @author shaoqiping
	 * @date 2017年9月8日下午4:19:57
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/statementPay", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void orderPayment(HttpServletRequest request, HttpServletResponse response, AgencyBillEntity billEntity) {
		try {
			if (billEntity == null || billEntity.getAmount() == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请填写必要信息");
				return;
			}
			billEntity.setFacId(getCurrentAgencyUser().getFacId());
			billEntity.setAgeId(getCurrentAgencyUser().getAgeId());
			List<OrderPaymentEntity> needPays = billService.findUnfinished(billEntity.getFacId(),
					billEntity.getAgeId());
			BigDecimal amount = BigDecimal.ZERO;
			for (OrderPaymentEntity orderPaymentEntity : needPays) {
				amount = amount.add(orderPaymentEntity.getNeedPay());
			}
			if (amount.compareTo(billEntity.getAmount()) < 0) {
				doResult(response, false, StatusCode.SAVEERROR, null, "还款金额大于所欠金额");
				return;
			}
			billEntity.setTransTime(new Date());
			boolean temp = getCurrentAgencyUser().getAgencySetup().getReceivablesFlag() > 0;
			boolean confirm = false;
			if (!temp) {
				if (billEntity.getTransMode() <= AgencyBill.CONFIRM) {
					billEntity.setConfirmTime(new Date());
					billEntity.setConfirmAmount(billEntity.getAmount());
					billEntity.setStatus(AgencyBill.STATUS);
					confirm = true;
				}
			}
			billEntity.setTransInfo(AgencyBill.REPAYMENT);
			boolean flag = billService.orderPayment(billEntity, confirm);
			if (flag) {
				doResult(response, true, StatusCode.SAVESUCCESS, null, "还款成功");
			} else {
				doResult(response, false, StatusCode.SAVEERROR, null, "还款失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:删除未确认的流水
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author shaoqiping
	 * @date 2017年8月24日下午5:38:12
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/deleteUnconfirmed", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void deleteUnconfirmed(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			if (id == null || LongUtils.isEmpty(id)) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			boolean flag = billService.deleteUnconfirmed(id, getCurrentAgencyUser().getAgeId());
			if (flag) {
				doResult(response, true, StatusCode.REMOVESUCCESS, null, ResultType.REMOVE_SUCCESS);
			} else {
				doResult(response, false, StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}

	}

	/**
	 * Description:条件分页查询
	 * 
	 * @param request
	 * @param response
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param filterText
	 * @param startTime
	 * @param endTime
	 * @param entity
	 * @author shaoqiping
	 * @date 2017年8月21日下午2:13:42
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findList", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, Integer page, Integer rows,
			String sort, String order, String filterText, String startTime, String endTime, AgencyBillVo entity) {
		try {
			// page默认为1 rows默认为10
			if (page == null || page <= 0) {
				page = 1;
			}
			if (rows == null || rows <= 0) {
				rows = 10;
			}
			PageUtils<AgencyBillVo> pageinfo = new PageUtils<AgencyBillVo>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("filterText", filterText);
			condition.put("facId", getCurrentAgencyUser().getFacId());
			condition.put("ageId", getCurrentAgencyUser().getAgeId());
			condition.put("startTime", startTime);
			condition.put("endTime", endTime);
			condition.put("status", entity.getStatus());
			condition.put("transInfo", entity.getTransInfo());
			condition.put("flag", AgencyBill.AGE);
			pageinfo.setCondition(condition);

			billService.findList(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
}
